package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import netscape.javascript.JSObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";
    @Autowired
    private WeChatProperties weChatProperties;

    public static final String GRANT_TYPE = "authorization_code";

    @Autowired
    private UserMapper userMapper;


    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {
        String openid = getOpenid(userLoginDTO);

        //判断openid是否为空，如果为空则登录失败
        if (openid == null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }else {
            User user = userMapper.getByOpenid(openid);
            //判断是否为新用户
            if (user == null){
                user = User.builder()
                        .openid(openid)
                        .createTime(LocalDateTime.now())
                        .build();
                //如果是新用户，自动完成注册
                userMapper.insert(user);
                user.setId(user.getId());
                return user;
            }else {
                return user;
            }
        }

    }


    //获取微信用户openid,单独封装成方法
    private String getOpenid(UserLoginDTO userLoginDTO) {
        //调用微信接口，获取openid
        Map<String, String> query = new HashMap<>();
        query.put("appid", weChatProperties.getAppid());
        query.put("secret", weChatProperties.getSecret());
        query.put("js_code", userLoginDTO.getCode());
        query.put("grant_type", GRANT_TYPE);
        //返回值为JSON字符串
        String result = HttpClientUtil.doGet(WX_LOGIN, query);
        //将JSON字符串转换为JSON对象
        JSONObject jsonObject = JSON.parseObject(result);
        //获取openid
        String openid = jsonObject.getString("openid");
        return openid;
    }
}
